<template>
	<div class="login">
		<header>UNI-ADMIN</header>
		<el-form :model="user" :rules="rules" ref="loginForm">
			<el-form-item prop="username">
				<el-input type="text" prefix-icon="el-icon-user" placeholder="请输入用户名" v-model="user.username"></el-input>
			</el-form-item>
			<el-form-item prop="password">
				<el-input type="password" prefix-icon="el-icon-lock" placeholder="请输入密码" v-model="user.password"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" style="width: 100%;" @click="login('loginForm')" :loading="loading">
					{{loading ?'登录中...' : '立即登录'}}
				</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	export default {
		// 组件名称
		name: 'demo',
		// 组件参数 接收来自父组件的数据
		props: [],
		// 局部注册的组件
		components: {},
		// 组件状态值
		data() {
			return {
				loading:false,
				user: {
					username: "admin",
					password: "admin",
				},
				// 规则校验
				rules:{
					username:[{required:true,message:"请输入用户名",trigger:"blur"}],
					password:[{required:true,message:"请输入密码",trigger:"blur"}],
				}
			}
		},
		mounted() {

		},
		// 计算属性
		computed: {},
		// 侦听器
		watch: {},
		// 组件方法
		methods: {
			// 登录
            login(formName){
				this.$refs[formName].validate(valid=>{
					if(valid){
						this.loading=true
						this.$axios.post('/api/login',this.user).then(res => {
							console.log(res)
							if(res.data.status==1){
								// 登录成功提示
								this.$message.success("登录成功")
								let data={
									username:res.data.username,
									token:res.data.token,
								}
								// 将token值存储值vuex中
								this.$store.commit('SetToken',data);
								// 跳转至后台首页
								this.$router.push('/demo/index')
								this.loading=false
							}
						}).catch((error)=>{
							this.loading=false
							// 捕获错误信息
							this.$message.error(error.response.data.msg);
						})
					}else{
						return false
					}
				})
			}
		},
		/**
		 * 组件实例创建完成
		 */
		created() {},
	}
</script>

<style lang="scss" scoped>
	.login {
		width: 36%;
		border: 1px solid #CCCCCC;
		box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);

		header{
			width: 100%;
			border-bottom: 1px solid #CCCCCC;
			line-height: 50px;
			text-align: center;
			font-weight: bold;
			font-size: 30px;
		}
		
		.el-form{
			width: 100%;
			padding: 15px;
			box-sizing: border-box;
		}
	}
</style>
